
#include "stdafx.h"
#include "RF_Interpret.h"
#define RW_TMAX  10
#define RW_LMAX  5
unsigned char m_RWFeature[RW_TMAX][RW_LMAX] ={

	0x00,0x00,0x00,0x00,0x00,//0
	0x00,0x00,0x00,0x00,0x00,//1
	0x9c,0x9d,0x00,0x00,0x00,//2
	0x9f,0x00,0x00,0x00,0x00,//3
	0x00,0x00,0x00,0x00,0x00,//4
	0xa0,0xa1,0x00,0x00,0x00,//5
	0x00,0x00,0x00,0x00,0x00,//6
	0x00,0x00,0x00,0x00,0x00,//7
	0x00,0x00,0x00,0x00,0x00,//8
	0x00,0x00,0x00,0x00,0x00 //9 
};

RF_Interpret::RF_Interpret(){

	
}

RF_Interpret::~RF_Interpret(){

}

int RF_Interpret::RF_FindChar( unsigned char * pData, unsigned char ch , int len ){

	int pos = 0,i =0;

	for( i =0;i < len ; i ++ ){

		if( pData[i] == ch ){

			return i ;
		}
	}

	return 0;
}

unsigned char RF_Interpret::RF_GetFeatureCode( unsigned char templeid, unsigned char index ){

	unsigned char featurecode = 0;

	if( templeid < RW_TMAX && index < RW_LMAX ){

		featurecode = m_RWFeature[templeid][index];
	}

	return featurecode;
}

unsigned char RF_Interpret::RF_ComputeFcc( unsigned char *pData, unsigned char uLen ){

	unsigned char i = 0;
	unsigned char fcc = 0x00;

	for (i = 0; i < uLen; i++) {
		fcc += pData[i];         
	}

	fcc = 0xff - fcc + 0x01;

	return fcc;

}

int	RF_Interpret::RF_InterpretRWDataToProtcol( unsigned char *pDest,
											   unsigned int   uESLId,
											   unsigned char  uTempleid,
											   unsigned char  *pData,
											   unsigned int    uLen){

	unsigned char t_bag =0, i_bag = 0,i_brk  = 0,i_pa = 0,i_ch =0,i_to =0,len =0;

	t_bag = ( uLen /55 ) + 1;


	pDest[1] = 0;
	pDest[2] = 0;
	pDest[3] = uESLId;
	pDest[4] = ( 0 << 7 )|( 1 << 5 )|(0x03);

	for( i_bag =0; i_bag < t_bag; i_bag ++ ){

		pDest[5] = ( t_bag << 4 ) |( i_bag + 1 );

		pDest[6] = (uTempleid << 0);

		i_brk = RF_FindChar( pData,',',uLen);

		if( i_brk == 0 ){
			
			i_brk = uLen;
		}

		i_pa  = 7;i_ch = 0,i_to = 0;

		while( i_brk ){

			pDest[i_pa + 0] = RF_GetFeatureCode(uTempleid,i_to++);
			pDest[i_pa + 1] = i_brk;
			memcpy( &pDest[i_pa + 2],&pData[i_ch],i_brk );


			i_pa = i_pa + 2+i_brk;
			i_ch = i_ch + i_brk +1;

			pDest[0] = i_pa ;

			if( i_ch < uLen ){

				len   = uLen - i_brk;

				i_brk = RF_FindChar( &pDest[i_ch],',',len );

				if( i_brk == 0 ){

					i_brk = uLen - i_ch;
				}		
			}
			else{

				i_brk = 0;
			}
		}
		pDest[pDest[0]] =RF_ComputeFcc( pDest, (pDest[0]) );
	}
	return (pDest[0] + 1);
}